#pragma once
#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <strings.h>
#include <functional>
#include "log.hpp"
#include "inetaddr.hpp"
using namespace hllog;
using namespace hladdr;
using Task_t = std::function<void(int, const std::string &, InetAddr &)>;
class UdpServer
{
public:
    UdpServer(uint16_t port, Task_t func) : _sockfd(-1), _port(port), _task(func)
    {
    }
    ~UdpServer() {}
    void Init()
    {
        // 1. 创建socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0); // AF_INET 网络通信  SOCK_DGRAM  面向数据报
        if (_sockfd < 0)
        {
            LOG(Level::DEBUG) << "socket error";
            exit(1);
        }
        LOG(Level::DEBUG) << "socket success, sockfd : " << _sockfd;
        InetAddr addr(_port);
        // 2.2 绑定IP、端口号
        int n = bind(_sockfd, addr.GetInetAddr(), addr.GetLen());
        if (n < 0)
        {
            LOG(Level::DEBUG) << "bind error";
            exit(2);
        }
        LOG(Level::DEBUG) << "socket success";
    }
    void Start()
    {
        while (true)
        {
            char buff[256];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 接受信息
            int n = recvfrom(_sockfd, buff, sizeof(buff), 0, (struct sockaddr *)&peer, &len);
            if (n < 0)
            {
                LOG(Level::WARNING) << "recvfrom error";
                continue;
            }
            buff[n] = '\0';
            InetAddr client(peer);
            LOG(Level::INFO) << client.ToString() <<" : "<<buff << buff;
            _task(_sockfd, buff, client);
        }
    }

private:
    int _sockfd;
    uint16_t _port;
    Task_t _task;
};
